package com.link.server.ws;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.stereotype.Component;

@Component
public class WebSocketNettyServer {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1); // 接收连接
    EventLoopGroup workerGroup = new NioEventLoopGroup(); // 处理 I/O
    public void init() {
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<>() {
                        @Override
                        protected void initChannel(Channel ch) {
                            ChannelPipeline pipeline = ch.pipeline();

                            // HTTP 编解码
                            pipeline.addLast(new HttpServerCodec());
                            // 支持大文件传输
                            pipeline.addLast(new ChunkedWriteHandler());
                            // 将多个消息转换为单一的 FullHttpRequest 或 FullHttpResponse
                            pipeline.addLast(new HttpObjectAggregator(65536));

                            // WebSocket 握手和协议处理
                            pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));

                            // 自定义消息处理器
                            pipeline.addLast(new WebSocketFrameHandler());
                        }
                    });

            Channel ch = b.bind(8888).sync().channel();
            System.out.println("WebSocket Server started at http://localhost:" + 8888 + "/ws");
            ch.closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
